const jwt = require('jsonwebtoken');
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
const router = new Router();
const secret = 'secret';
const fs = require('fs');

const privateKey = fs.readFileSync('./private.key', 'utf8');
const publicKey = fs.readFileSync('./public.key', 'utf8');

let user = {
    name: 'zhangsan',
    age: 18
};
const token = jwt.sign(user, privateKey,{   // 签发token
    expiresIn: 60 * 600 ,    // 过期时间
    algorithm: "RS256"  //签名算法
}); // 签发token
router.post('/重学css', async (ctx, next) => {
    ctx.body = {
        token
    }
});

router.post('/test', async (ctx, next) => {
    const token = ctx.request.headers.authorization.replace('Bearer ', '');
    try {
        const result = jwt.verify(token, publicKey, {   // 验证token
            algorithms: ["RS256"]   //签名算法
        });
        console.log(result);
        ctx.body = {
            code: 200,
            data: result
        }
    } catch (e) {
        ctx.body = {
            code: 500,
            data: e,
            message: 'token验证失败'
        }
    }
});
app.use(router.routes());

app.listen(3000, () => {
    console.log('server is running at port 3000');
})